/*
 * @Author: your name
 * @Date: 2021-05-12 09:21:59
 * @LastEditTime: 2021-05-13 18:02:38
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \koa2-serve\controller\user.js
 */
const jwt = require("jsonwebtoken");
const { secret } = require("../config.js");
const User = require("../model/user.js");

class UserController {
    /**
     * @description: 用户登录
     * @param {*} ctx
     * @return {*}
     */
    static async login(ctx) {
        let request = ctx.request.body;
        if (!request.userName) {
            return ctx.error({ msg: "用户未定义!" });
        }
        let user = await User.findOne({ userName: request.userName });
        if (user) {
            // if(user.password!==request.password){
            //     return ctx.error({ msg: '密码错误!' });
            // }else{
            // }
            const token = jwt.sign(
                {
                    userName: user.userName,
                    id: user._id,
                },
                secret.jwtKey,
                { expiresIn: "1h" }
            );
            return ctx.success({
                msg: "登录成功!",
                data: { token: "Bearer " + token },
            });
        } else {
            return ctx.error({ msg: "用户不存在!" });
        }
    }
    /**
     * @description:获取所有数据
     * @param {*} ctx
     * @return {*}
     */
    static async getAllUser(ctx) {
        // ctx.body = await User.find({})
        const data = await User.find({});
        return ctx.success({ msg: "请求成功!", data });
    }
    /**
     * @description:根据id查找
     * @param {*} ctx
     * @return {*}
     */
    static async getUserById(ctx) {
        let id = ctx.query.id;
        let user = await User.findOne({ id: id });
        if (user) {
            // ctx.body = user;
            return ctx.success({ msg: "请求成功!", data: user });
        } else {
            return ctx.error({ msg: "用户不存在!" });
        }
    }
    /**
     * @description:添加用户
     * @param {*} ctx
     * @return {*}
     */
    static async saveUser(ctx) {
        let request = ctx.request.body;
        if (!request.userName) {
            return ctx.error({ msg: "用户未定义!" });
        }
        let user = new User({
            userName: request.userName,
            age: request.age,
            tags: request.tags,
        });
        user = await user.save();
        return ctx.success({ msg: "保存成功!", data: user });
    }
}
module.exports = UserController;
